package com.itheima.tlias84.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.utils.JwtUtil;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录过滤器，进行登录token拦截
 */
@Slf4j
@Component
public class LoginFilter implements Filter {

    @Resource
    EmpMapper empMapper;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("开始执行http请求过滤");
        //参数向下转型成HttpServletRequest 以及 HttpServletResponse
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //放行登录接口
        String requestURI = httpServletRequest.getRequestURI();
        if (requestURI.contains("login")) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }


        //获取请求头中的token
        String token = httpServletRequest.getHeader("token");

        //判断是否有token ->是否绕过登录
        if (Objects.isNull(token)) {
            httpServletResponse.setContentType("application/json; charset = UTF-8");
            httpServletResponse.setCharacterEncoding("UTF-8");
            //设置响应状态码
            httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            PrintWriter writer = httpServletResponse.getWriter();

            ResultUtil fail = ResultUtil.fail("请先登录");
            writer.write(JSONObject.toJSONString(fail));
            return;
        }
        //解析token对不对 与密码对不对
//        JSONObject jsonObject = JwtUtil.verifyToken(token);
//        String username = (String) jsonObject.get("username");
//        String password = (String) jsonObject.get("password");
//        try {
        // 解析token


        try {
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUserName(jsonObject.getString("username"));
            if (Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))){
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
                PrintWriter writer = httpServletResponse.getWriter();
                ResultUtil fail = ResultUtil.fail("无效的token");
                writer.write(JSONObject.toJSONString(fail));
                return;
            }
        }catch (Exception e){
            httpServletResponse.setContentType("application/json; charset=UTF-8");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
            PrintWriter writer = httpServletResponse.getWriter();
            ResultUtil fail = ResultUtil.fail("无效的token");
            writer.write(JSONObject.toJSONString(fail));
            return;
        }

        // 验证token是否有效
//            if (jsonObject == null || jsonObject.isEmpty()) {
//                httpServletResponse.setContentType("application/json; charset=UTF-8");
//                httpServletResponse.setCharacterEncoding("UTF-8");
//                httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
//                PrintWriter writer = httpServletResponse.getWriter();
//                ResultUtil fail = ResultUtil.fail("无效的token");
//                writer.write(JSONObject.toJSONString(fail));
//                return;
//            }

        // token有效，继续处理请求
//            filterChain.doFilter(httpServletRequest, httpServletResponse);


//        } catch (Exception e) {
//            log.error("Token验证失败: {}", e.getMessage());
//            httpServletResponse.setContentType("application/json; charset=UTF-8");
//            httpServletResponse.setCharacterEncoding("UTF-8");
//            PrintWriter writer = httpServletResponse.getWriter();
//            ResultUtil fail = ResultUtil.fail("Token验证失败");
//            writer.write(JSONObject.toJSONString(fail));
//            return;
//        }


        //过滤链对象执行完过滤逻辑之后放行http请求，吧request和response 重新交给controller（servlet）
        filterChain.doFilter(servletRequest, servletResponse);
        log.info("过滤完成");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("初始化过滤器");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
